package chat;

import com.alibaba.fastjson.JSON;
import domain.Message;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 聊天室
 */
@ServerEndpoint("/chat")
public class ChatEndpoint {
    private static List<Session> sessions = new ArrayList<>();
    private static List<String> names = new ArrayList<>();
    private static String username = null;

    @OnOpen
    public void open(Session session) {
        String string = session.getQueryString();
        //获取用户名
        username = string.split("=")[1];
        this.names.add(username);
        //每个用户的session存储起来
        this.sessions.add(session);
        String welcome="欢迎"+username+"进入聊天室";
        //封装消息
        Message message=new Message();
        message.setUsername(this.names);
        message.setWelcome(welcome);
        //转为json
        String jsonString = JSON.toJSONString(message);
        this.broadcast(sessions,jsonString);
        System.out.println(username);
    }
    public void broadcast(List<Session> sessions,String msg){
        Iterator<Session> iterator = sessions.iterator();
        try {
            while (iterator.hasNext()){
                Session session = iterator.next();
                session.getBasicRemote().sendText(msg);
            }
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }
    @OnMessage
    public void message(Session session,String msg) throws IOException {
        Message message=new Message();
        message.setContent(msg);
        message.setUsername(this.names);
        String string = JSON.toJSONString(message);
        this.broadcast(sessions,string);
    }
    @OnClose
    public void close(Session session){
        this.sessions.remove(session);
        this.names.remove(this.username);
        String str="欢送"+this.username+"离开聊天室";
        Message message=new Message();
        message.setWelcome(str);
        message.setUsername(this.names);
        String msg=JSON.toJSONString(message);
        broadcast(this.sessions,msg);
    }
}
